package co.za.itweb.securedata;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class Splash extends FragmentActivity {
	InputStream is = null;
	String result = "";
	boolean parsed = false;

	LoadTask lt;
	
	private String splashdensity;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		
		if (internetConnection()) {
            if(!hasStorage(true)){
            	Toast.makeText(getApplicationContext(), "SD card is not writable, reverting to default icons...",
    					Toast.LENGTH_LONG).show();
            }
			lt = new LoadTask(Splash.this);
			lt.execute();

		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"There is no internet connection.Please connect to the internet and try again.")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									dialog.cancel();
									finish();
								}

							});
			AlertDialog alert = builder.create();
			alert.show();
		}

	}

	

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}
	
	

	public boolean parseConfig() {
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(First.url);

			JSONObject obj = new JSONObject();
			obj.put("conf", "conf");
			httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

			httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");

			}
			
			
			is.close();
			result = sb.toString();
			//System.out.println(result);
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			First.jArray = new JSONObject(result).getJSONObject("company");
			First.FOLDERNAME= First.jArray.getJSONObject("path").getString("unique");
			First.FEEDS= First.jArray.getJSONObject("xml_feed");
			First.ICONPACK = First.jArray.getJSONObject("images").getJSONObject("icon");
			First.COMPANYNAME = First.jArray.getString("name");
			
			First.STARTCOLOR = "#ff"+First.jArray.getJSONObject("color").getJSONObject("topbar").getJSONObject("background").getString("start");
			First.ENDCOLOR ="#ff"+First.jArray.getJSONObject("color").getJSONObject("topbar").getJSONObject("background").getString("end");
			First.PATH = "http://itweb.mobi/_feed/vpo/securedata/"+First.jArray.getJSONObject("path").getString("android");
			First.LOGONAME = First.jArray.getJSONObject("images").getString("logo");
			
			//First.SPLASHNAME = First.jArray.getJSONObject("images").getString("splash");
			//First.SPLASHBACKGROUNDSTART = "#ff"+First.jArray.getJSONObject("color").getJSONObject("splash").getJSONObject("background").getString("start");
			//First.SPLASHBACKGROUNDEND = "#ff"+First.jArray.getJSONObject("color").getJSONObject("splash").getJSONObject("background").getString("end");
			
			First.BACKGROUND = "#ff"+First.jArray.getJSONObject("color").getJSONObject("body").getJSONObject("background").getString("start");

			//First.ACTIONMENUPATH = First.jArray.getString("actionmenupath");
			First.ACTIONMENUBACKGROUNDCOLORSTART = "#ff"+First.jArray.getJSONObject("color").getJSONObject("menu").getJSONObject("action").getJSONObject("background").getString("start");
			First.ACTIONMENUBACKGROUNDCOLOREND = "#ff"+First.jArray.getJSONObject("color").getJSONObject("menu").getJSONObject("action").getJSONObject("background").getString("end");
			First.ACTIONMENUTEXTCOLOR = "#ff"+First.jArray.getJSONObject("color").getJSONObject("menu").getJSONObject("action").getJSONObject("foreground").getString("text");
			
			First.BACKGROUNDTEXTCOLOR = "#ff"+First.jArray.getJSONObject("color").getJSONObject("body").getJSONObject("foreground").getString("text");
			First.LISTTEXTCOLOR ="#ff"+First.jArray.getJSONObject("color").getJSONObject("list").getJSONObject("foreground").getString("text");
			
			First.TOPBARTEXTCOLOR = "#ff"+First.jArray.getJSONObject("color").getJSONObject("topbar").getJSONObject("foreground").getString("text");
			
			First.PAGE1TITLE=  First.jArray.getJSONObject("page").getJSONObject("page_1").getString("title");
			First.PAGE2TITLE=  First.jArray.getJSONObject("page").getJSONObject("page_2").getString("title");
			First.PAGE3TITLE=  First.jArray.getJSONObject("page").getJSONObject("page_3").getString("title");
			First.PAGE4TITLE=  First.jArray.getJSONObject("page").getJSONObject("page_4").getString("title");
			First.PAGE4TEXT=  First.jArray.getJSONObject("page").getJSONObject("page_4").getString("text");
			First.PAGE4URL=  First.jArray.getJSONObject("page").getJSONObject("page_4").getString("url");
			First.PAGE5TITLE=  First.jArray.getJSONObject("page").getJSONObject("page_5").getString("title");
			First.PAGE5TEXT=  First.jArray.getJSONObject("page").getJSONObject("page_5").getString("text");
			First.PAGE5URL=  First.jArray.getJSONObject("page").getJSONObject("page_5").getString("url");
			First.GPSMARKERS=  First.jArray.getJSONObject("gps");
			
			First.MYWEB = First.jArray.getJSONObject("page").getJSONObject("page_5").getString("url");
			First.ABOUTUS = First.jArray.getJSONObject("page").getJSONObject("page_4").getString("url");
			
			First.INFO=  First.jArray.getJSONObject("info");
			
			
			return true;

		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);
			First.List.clear();
			First.jArray = null;
			
			is = null;
			finish();
		}

		return false;

	}

	
	
	

	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			splashdensity = "ldpi";
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			splashdensity = "mdpi";
			break;
		case DisplayMetrics.DENSITY_HIGH:
			splashdensity = "hdpi";
			break;
		case DisplayMetrics.DENSITY_XHIGH:
			splashdensity = "xdpi";
			break;

		}
		return splashdensity;
	}

	public static RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			
			return null;
		}
	}

	private class LoadTask extends AsyncTask<Void, Integer, Void> {
		RSSFeed feed;
		RSSFeed feed2;

		

		public LoadTask(Splash activity) {
			

		}

		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			if (parseConfig()) {
			
				try {
					JSONArray xmlFeeds=First.FEEDS.getJSONArray("feed");
					
					for(int t=0;t<xmlFeeds.length();t++){
						JSONObject row = xmlFeeds.getJSONObject(t);
						feed = getFeed(row.getString("url"));
						if (feed != null) {
							First.List.add(feed);
						}
					}


					if (hasStorage(true)) {

						if (!First.List.isEmpty()) {
							String iconString = "";
							try {
								
								
							for (int i = 0; i < First.ICONPACK.length(); i++) {
							    JSONObject mynewsobject = First.ICONPACK.getJSONObject("my_news");
							    iconString = mynewsobject.getString("default")+"|";
							    First.mynewsname=mynewsobject.getString("default");
							   
							    
							    JSONObject sectornewsobject = First.ICONPACK.getJSONObject("sector_news");
							    iconString += sectornewsobject.getString("default")+"|";
							    First.sectornewsname=sectornewsobject.getString("default");
							   
							    
							    JSONObject findusobject = First.ICONPACK.getJSONObject("find_us");
							    iconString += findusobject.getString("default")+"|";
							    First.findusname=findusobject.getString("default");
							   
							    
							    JSONObject aboutusobject = First.ICONPACK.getJSONObject("about_us");
							    iconString += aboutusobject.getString("default")+"|";
							    First.aboutusname=aboutusobject.getString("default");
							    
							    JSONObject mywebobject = First.ICONPACK.getJSONObject("my_web");
							    iconString += mywebobject.getString("default")+"|";
							    First.mywebname=mywebobject.getString("default");
							    
							    JSONObject favoriteobject = First.ICONPACK.getJSONObject("favourite");
							    iconString += favoriteobject.getString("default")+"|";
							    First.favoritename=favoriteobject.getString("default");
							    iconString += favoriteobject.getString("active")+"|";
							    First.addfavoritename=favoriteobject.getString("active");
							    iconString += favoriteobject.getString("inactive")+"|";
							    First.addedfavoritename=favoriteobject.getString("inactive");
							    
							    JSONObject refreshobject = First.ICONPACK.getJSONObject("refresh");
							    iconString += refreshobject.getString("default")+"|";
							    First.refreshname=refreshobject.getString("default");
							    
							    JSONObject menuobject = First.ICONPACK.getJSONObject("menu");
							    iconString += menuobject.getString("default")+"|";
							    First.menuname=menuobject.getString("default");
							    
							    JSONObject backobject = First.ICONPACK.getJSONObject("back");
							    iconString += backobject.getString("default")+"|";
							    First.backname=backobject.getString("default");
							    
							    JSONObject emailobject = First.ICONPACK.getJSONObject("email");
							    iconString += emailobject.getString("default")+"|";
							    First.emailname=emailobject.getString("default");
							    
							    JSONObject twitterobject = First.ICONPACK.getJSONObject("twitter");
							    iconString += twitterobject.getString("default")+"|";
							    First.twittername=twitterobject.getString("default");
							    iconString += twitterobject.getString("inactive")+"|";
							    First.twittervisitedname=twitterobject.getString("inactive");
							    
							    JSONObject closeobject = First.ICONPACK.getJSONObject("close");
							    iconString += closeobject.getString("default")+"|";
							    First.closename=closeobject.getString("default");
								  
								}
							
							String[] icons = iconString.split("\\|");
							File storagePath = new File(Environment
									.getExternalStorageDirectory().getPath()
									+"/"+First.FOLDERNAME);
							storagePath.mkdirs();

							for (int x = 0; x < 15; x++) {
//								File savedfile = new File(storagePath,
//										icons[x].toString());

					

									URL url;
									try {
										url = new URL(First.PATH+"images/"
												+ determineDensity() + "/"
												+ icons[x]);

										

										InputStream input = url.openStream();

										File file = new File(storagePath,
												icons[x].toString());

										if (!file.exists()) {
											file.delete();
										}

										OutputStream output = new FileOutputStream(
												file);

										byte[] buffer = new byte[1500];

										try {
											int bytesRead = 0;
											while ((bytesRead = input.read(
													buffer, 0, buffer.length)) >= 0) {
												output.write(buffer, 0,
														bytesRead);

											}
										} finally {
											output.close();
											buffer = null;
										}

									} catch (Exception ex) {
										publishProgress(1);
										

									}

						

							}// end for
							
							} catch (JSONException e1) {
								
								e1.printStackTrace();
							}

						}

					} else {// end if card mounted
						Intent returnIntent = new Intent();
						returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						setResult(RESULT_CANCELED, returnIntent);
						publishProgress(2);

					}
					

				} catch (Exception ee) {

					ee.printStackTrace();

				}

				if (isCancelled()) {
					
					File storagePathdelete = new File( Environment
							.getExternalStorageDirectory().getPath()
							+ "/"+First.FOLDERNAME+"/");
					deleteAllIcons(storagePathdelete);
					First.List.clear();
					First.jArray = null;
					result = "";
					is = null;
                    
					finish();

					return null;
				}

			} else {
				
				First.List.clear();
				First.jArray = null;
				result = "";
				is = null;

				Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_CANCELED, returnIntent);
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

			if (values[0] == 1) {
				Toast.makeText(getApplicationContext(), "Some of the icons failed to download, reverting to default ones...",Toast.LENGTH_SHORT ).show();

			}
			if (values[0] == 2) {
				Toast.makeText(getApplicationContext(), "There was a problem writing to device SD card, you will not be able to see all news ...",Toast.LENGTH_SHORT ).show();

			}
			

		}

		@Override
		protected void onPostExecute(Void result) {
            if(First.List.size()!=0){
			System.out.println("FINITO" + First.List.toString());
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_OK, returnIntent);
			
			finish();
            }else{
            	Intent returnIntent = new Intent();
				returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_CANCELED, returnIntent);
				First.List.clear();
				First.jArray = null;
				
				is = null;
				finish();
            }

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if (lt.getStatus() == AsyncTask.Status.RUNNING ) {

				lt.cancel(true);
			}

			File storagePathdelete = new File( Environment
					.getExternalStorageDirectory().getPath()
					+ "/"+First.FOLDERNAME+"/");
			deleteAllIcons(storagePathdelete);
			Intent returnIntent = new Intent();
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			setResult(RESULT_CANCELED, returnIntent);
			finish();

		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		if (lt.getStatus() == AsyncTask.Status.RUNNING) {

			lt.cancel(true);
		}
		File storagePathdelete = new File( Environment
				.getExternalStorageDirectory().getPath()
				+ "/"+First.FOLDERNAME+"/");
		deleteAllIcons(storagePathdelete);
		Intent returnIntent = new Intent();
		returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		setResult(RESULT_CANCELED, returnIntent);

		finish();
		return;
	}

	
	
	static public boolean hasStorage(boolean requireWriteAccess) {
	
		String state = Environment.getExternalStorageState();
		System.out.println("storage state is " + state);

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (requireWriteAccess) {
				boolean writable = checkFsWritable();
				System.out.println("storage writable is " + writable);
				return writable;
			} else {
				return true;
			}
		} else if (!requireWriteAccess
				&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	private static boolean checkFsWritable() {
	
		String directoryName = Environment.getExternalStorageDirectory()
				.toString() + "/"+First.FOLDERNAME+"/";
		File directory = new File(directoryName);
		if (!directory.isDirectory()) {
			if (!directory.mkdirs()) {
				return false;
			}
		}
		return directory.canWrite();
	}

	
	public void deleteAllIcons(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				new File(dir, children[i]).delete();
				
			}
		}
	}
	 
	
	  
}